package com.ctrip.ec.biz.dao.goods;
import com.ctrip.ec.dal.DaoBase;
import com.ctrip.ec.biz.entity.goods.GoodsSpecEntity;
import com.ctrip.ec.dal.DbAccess;
import com.ctrip.ec.dal.IdConvert;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class GoodsSpecDao extends DaoBase<GoodsSpecEntity> {
    public GoodsSpecDao() {
        super(GoodsSpecEntity.class);
    }
    public GoodsSpecDao(DbAccess db) {
        super(GoodsSpecEntity.class,db);
    }

    public List<GoodsSpecEntity> listByGoodsId(Long id) throws SQLException {
        String sql = "select * from "  + this.getTableName() + " where goods_id=?";
        List<GoodsSpecEntity> list = this.getDb().query(GoodsSpecEntity.class,sql,id);
        return list;
    }

//    public void releaseStoreCount(Integer goodsNum, Long specId) throws SQLException {
//        String sql = "update " + this.getTableName() + "set store_count=store_count - " + goodsNum + " where id=$0";
//        this.db.execute(sql,specId);
//    }

    public List<GoodsSpecEntity> listWithLock(List<Long> specIds) throws SQLException {
        if(specIds != null && specIds.size()>0) {
            String sql = "select * from " + this.getTableName() + " where id in (" + IdConvert.join(specIds) + ") for update";
            return this.db.query(GoodsSpecEntity.class,sql);
        }else{
            return new ArrayList<>();
        }

    }

    public GoodsSpecEntity entityWithLock(Long id) throws SQLException {
        String sql = "select * from "  + this.getTableName() + " where id =? for update";
        List<GoodsSpecEntity> list = this.db.query(GoodsSpecEntity.class,sql,id);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    public List<GoodsSpecEntity> sumStoreCount(List<Long> goodsIds) throws SQLException {
        if(goodsIds!= null && goodsIds.size()>0) {
            String strIds = IdConvert.join(goodsIds);
            String sql = "select goods_id,store_count from " + this.getTableName() + " where goods_id in (" + strIds+ ")";
            List<GoodsSpecEntity> list = this.db.query(GoodsSpecEntity.class,sql);
            Map<Long,List<GoodsSpecEntity>> map = list.stream().collect(Collectors.groupingBy(t->t.getGoodsId()));

            List<GoodsSpecEntity> list2= new ArrayList<>();
            for(Map.Entry<Long,List<GoodsSpecEntity>> entry :map.entrySet()){
                GoodsSpecEntity entity = new GoodsSpecEntity();
                entity.setGoodsId(entry.getKey());
                entity.setStoreCount(entry.getValue().stream().mapToInt(t->t.getStoreCount()).sum());
                list2.add(entity);
            }

            return list2;
        }else{
            return null;
        }

    }
}
